import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/wallpaper360.dart';
import 'package:wallpaper/components/placeholder/appbar_base.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/model/image_base.dart';

class ImageList360 extends StatefulWidget {
  final String cids;
  final String title;
  const ImageList360({super.key, required this.cids, required this.title});

  @override
  State<ImageList360> createState() => _ImageList360State();
}

class _ImageList360State extends State<ImageList360> {
 final  List<ImageBase> imgs = [];
  bool isLoading = false;
  int pageno = 1;
  int count = 30;
  int totalPage = 1;

  Future<void> getData() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
    });
    try {
      Response res = await get360ImgList(
        cids: widget.cids,
        pageno: pageno,
        count: count,
      );
      if (res.statusCode == 200) {
        List<dynamic> list = res.data['data']['list'];
        setState(() {
          totalPage = res.data['data']['total_page'];
        });
        List<ImageBase> newData = list
            .map(
              (e) => ImageBase(
                largePath: e['url'],
                smallPath: e['url'],
                tags: e['tag'].replaceAll(',', ' '),
              ),
            )
            .toList();
        imgs.addAll(newData);
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppbarBase(title: widget.title),
      body: RepaintBoundary(
        child: ImageList(
          imageList: imgs,
          isLoading: isLoading,
          isPC: true,
          onImageBottomLoading: () {
            if (pageno < totalPage) {
              setState(() {
                pageno++;
              });
              getData();
            }
          },
          onImageListRefresh: () {
            setState(() {
              pageno = 1;
              imgs.clear();
            });
            getData();
          },
        ),
      ),
    );
  }
}
